package top.hzy520.online.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hzy520.common.constants.Constants;
import top.hzy520.common.exception.YuyuBuyException;
import top.hzy520.common.utils.RequestUtil;
import top.hzy520.online.dao.OnlineUserMapper;
import top.hzy520.online.entity.OnlineUser;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 0:24 2018/9/26
 */
@Service
public class OnlineServiceImpl implements OnlineService {

    @Autowired
    private OnlineUserMapper onlineUserMapper;

    @Override
    public int selectAllCount() {
        return onlineUserMapper.selectAllCount();
    }

    @Override
    public List<OnlineUser> selectAllOnlineUserList(int offset, int limit) {
        return onlineUserMapper.selectAllOnlineUserList(offset,limit);
    }

    @Override
    public void saveOnlineUser(String username, String sessionId, HttpServletRequest request) {
           OnlineUser onlineUser=new OnlineUser();
           onlineUser.setOnlineSessionId(sessionId);
           onlineUser.setLoginTime(new Date());
           onlineUser.setOnlineUsername(username);
           onlineUser.setOnlineIp(RequestUtil.getIpFromRequest(request));
           onlineUser.setSessionStatus(Constants.REQUEST_SESSION_STATUS_ONLINE);
           onlineUser.setOnlineBrowser(RequestUtil.getRequestBrowserInfo(request));
           onlineUser.setOnlineSystem(RequestUtil.getRequestSystemInfo(request));
           onlineUserMapper.insertSelective(onlineUser);
     }

    @Override
    public void forceLogout(String sessionId) {
        OnlineUser onlineUser=onlineUserMapper.selectUserBySessionId(sessionId);
        if (onlineUser!=null){
             onlineUser.setSessionStatus(Constants.REQUEST_SESSION_STATUS_UNONLINE);
             onlineUserMapper.updateByPrimaryKeySelective(onlineUser);
        }else {
            throw new YuyuBuyException("下线用户不存在");
        }
    }

    @Override
    public void deleteOnlineUser(List<OnlineUser> onlineUserList) {
        onlineUserMapper.deleteSelectedOnline(onlineUserList);
    }
}
